<template>
  <div>
    <div class="app-container">

      <!-- 搜索和新增按钮 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-input
            v-model="queryParams.snId"
            clearable
            placeholder="请输入产品SN码进行查询"
            @clear="getList"
            @keyup.enter.native="getList">
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-input
            v-model="queryParams.sendBackNumber"
            clearable
            placeholder="请输入订单号进行查询"
            @clear="getList"
            @keyup.enter.native="getList">
          </el-input>
        </el-col>

        <el-col :span="6">
          <el-button
            icon="el-icon-search"
            @click="getList">
            查询
          </el-button>
        </el-col>


        <el-col :span="6">
          <el-button
            icon="el-icon-plus"
            plain
            type="primary"
            @click="showAddForm">
            添加
          </el-button>
        </el-col>

        <el-col :span="6" class="load-failure-position">
          <el-button
            icon="el-icon-refresh-right"
            plain
            @click="loadFailureCondition">
            更新失效情况
          </el-button>
        </el-col>

      </el-row>


      <!--      信息表主体-->
      <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column align="center" label="订单号" prop="sendBackNumber"/>
        <el-table-column align="center" label="客户名称" prop="name"/>
        <el-table-column align="center" label="机器SN码" prop="snId"/>
        <el-table-column align="center" label="七天失效情况" prop="failureCondition"/>
        <el-table-column align="center" label="机器状态" prop="machineCondition">
          <template slot-scope="scope">
            <span v-if="scope.row.machineCondition === 1">未维修</span>
            <span v-else-if="scope.row.machineCondition === 2">已维修</span>
            <span v-else>未知状态</span> <!-- 防止出现意外值 -->
          </template>
        </el-table-column>

        <!-- 添加订单详情按钮 -->
        <el-table-column align="center" label="订单详情">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              size="mini"
              type="text"
              @click="showDetailsDialog(scope.row)">
              详情查询
            </el-button>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="300">
          <template slot-scope="scope">
            <el-button
              plain
              size="small"
              type="success"
              @click="openUpdateDialog(scope.row)">
              修改
            </el-button>

            <el-button
              plain
              size="small"
              type="warning"
              @click="openWeixiuDialog(scope.row)">
              维修
            </el-button>

            <el-button
              plain
              size="small"
              type="danger"
              @click="openWuliuDialog(scope.row)">
              发货
            </el-button>
          </template>
        </el-table-column>

      </el-table>


      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>


    <!-- 详情弹窗 -->
    <el-dialog
      :visible.sync="detailsDialogVisible"
      width="500px">
      <span slot="title" class="custom-dialog-title">详细信息</span>

      <el-form ref="detailsForm" :model="detailsForm" label-width="100px">

        <el-form-item label="品牌">
          <el-input v-model="detailsForm.brand" disabled></el-input>
        </el-form-item>
        <el-form-item label="尺寸">
          <el-input v-model="detailsForm.size" disabled></el-input>
        </el-form-item>
        <el-form-item label="机型">
          <el-input v-model="detailsForm.machineType" disabled></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="detailsForm.count" disabled></el-input>
        </el-form-item>
        <el-form-item label="具体现象">
          <el-input v-model="detailsForm.phenomenon" disabled></el-input>
        </el-form-item>
        <el-form-item label="附件状况">
          <el-input v-model="detailsForm.attachStatus" disabled></el-input>
        </el-form-item>
        <el-form-item label="返回地区">
          <el-input v-model="detailsForm.backLocation" disabled></el-input>
        </el-form-item>
        <el-form-item label="生产日期">
          <el-input v-model="detailsForm.manuDate" disabled></el-input>
        </el-form-item>
        <el-form-item label="退回日期">
          <el-input v-model="detailsForm.backDate" disabled></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailsDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>


    <!-- 修改信息弹窗 -->
    <el-dialog
      :visible.sync="updateDialogVisible"
      width="500px">
      <span slot="title" class="custom-dialog-title">修改订单信息</span>
      <el-form ref="updateForm" :model="updateForm" :rules="rulesUpdate" label-width="100px">
        <el-form-item label="机器SN码" prop="snId">
          <el-input v-model="updateForm.snId" disabled></el-input>
        </el-form-item>
        <el-form-item label="快递单号" prop="sendBackNumber">
          <el-input v-model="updateForm.sendBackNumber"></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="updateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="updateForm.brand"></el-input>
        </el-form-item>
        <el-form-item label="机型" prop="machineType">
          <el-input v-model="updateForm.machineType"></el-input>
        </el-form-item>
        <el-form-item label="尺寸" prop="size">
          <el-input v-model="updateForm.size"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input v-model="updateForm.count"></el-input>
        </el-form-item>
        <el-form-item label="生产日期" prop="manuDate">
          <el-date-picker
            v-model="updateForm.manuDate"
            type="date"
            placeholder="选择生产日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="附件状况" prop="attachStatus">
          <el-input v-model="updateForm.attachStatus"></el-input>
        </el-form-item>
        <el-form-item label="返回地区" prop="backLocation">
          <el-input v-model="updateForm.backLocation"></el-input>
        </el-form-item>
        <el-form-item label="具体现象" prop="phenomenon">
          <el-input v-model="updateForm.phenomenon"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">确定</el-button>
      </div>
    </el-dialog>


    <!-- 添加信息弹窗 -->
    <el-dialog
      :visible.sync="addDialogVisible"
      width="500px">
      <span slot="title" class="custom-dialog-title">添加订单信息</span>
      <el-form ref="addForm" :model="addForm" :rules="rulesAdd" label-width="100px">
        <el-form-item label="机器SN码" prop="snId">
          <el-input v-model="addForm.snId"></el-input>
        </el-form-item>
        <el-form-item label="快递单号" prop="sendBackNumber">
          <el-input v-model="addForm.sendBackNumber"></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="addForm.brand"></el-input>
        </el-form-item>
        <el-form-item label="机型" prop="machineType">
          <el-input v-model="addForm.machineType"></el-input>
        </el-form-item>
        <el-form-item label="尺寸" prop="size">
          <el-input v-model="addForm.size"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-input v-model="addForm.count"></el-input>
        </el-form-item>
        <el-form-item label="生产日期" prop="manuDate">
          <el-date-picker
            v-model="addForm.manuDate"
            type="date"
            placeholder="选择生产日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="附件状况" prop="attachStatus">
          <el-input v-model="addForm.attachStatus"></el-input>
        </el-form-item>
        <el-form-item label="返回地区" prop="backLocation">
          <el-input v-model="addForm.backLocation"></el-input>
        </el-form-item>
        <el-form-item label="具体现象" prop="phenomenon">
          <el-input v-model="addForm.phenomenon"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </div>
    </el-dialog>


    <!-- 维修信息弹窗 -->
    <el-dialog
      :visible.sync="weixiuDialogVisible"
      width="500px">
      <span slot="title" class="custom-dialog-title">记录维修检查信息</span>
      <el-form ref="weixiuForm" :model="weixiuForm" label-width="100px">
        <el-form-item label="产品条码" prop="snId">
          <el-input v-model="weixiuForm.snId" disabled></el-input>
        </el-form-item>
        <el-form-item label="机器实际故障" prop="brokedown">
          <el-input v-model="weixiuForm.brokedown"></el-input>
        </el-form-item>
        <el-form-item label="维修记录" prop="maintainRecord">
          <el-input v-model="weixiuForm.maintainRecord"></el-input>
        </el-form-item>
        <el-form-item label="不良原因" prop="badReason">
          <el-input v-model="weixiuForm.badReason"></el-input>
        </el-form-item>
        <el-form-item label="处理方式" prop="resolveMethod">
          <el-input v-model="weixiuForm.resolveMethod"></el-input>
        </el-form-item>
        <el-form-item label="责任归属" prop="responsibility">
          <el-select v-model="weixiuForm.responsibility" placeholder="请选择责任归属">
            <el-option label="材料" :value="1"></el-option>
            <el-option label="物流" :value="2"></el-option>
            <el-option label="客责" :value="3"></el-option>
            <el-option label="制程" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修人" prop="maintainMan">
          <el-input v-model="weixiuForm.maintainMan"></el-input>
        </el-form-item>
        <el-form-item label="维修网点" prop="maintainPoint">
          <el-select v-model="weixiuForm.maintainPoint" placeholder="请选择维修网点">
            <el-option label="黄石工厂" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="添加配件:" prop="partsInformation">
          <el-button
            round plain
            icon="el-icon-circle-plus-outline"
            size="small"
            @click="addPartsInfomation(weixiuForm.snId)">
            配件信息
          </el-button>
        </el-form-item>
        <el-form-item label="其他配件" prop="other">
          <el-input v-model="weixiuForm.other"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="weixiuDialogVisible = false">返回</el-button>
        <el-button type="primary" @click="submitWeixiu">提交</el-button>
      </div>
    </el-dialog>


    <!--    配件信息弹窗-->
    <el-dialog
      :visible.sync="partsTableVisible"
      width="1000px"
      class="partsTable-dialog">
      <span slot="title" class="custom-dialog-title">配件信息</span>
      <el-table :data="partsTableForm" style="width: 100%">
        <el-table-column align="center" label="配件名" prop="partsName"/>
        <el-table-column align="center" label="原配件SN码" prop="originPartsSnId"/>
        <el-table-column align="center" label="新配件SN码" prop="newPartsSnId"/>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-delete"
              type="danger"
              plain circle
              @click="deletePartsData(scope.row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer">
      <el-button @click="partsTableVisible = false">关闭</el-button>
      <el-button type="primary" @click="addParts">添加</el-button>
   </span>
    </el-dialog>


    <!--    添加配件信息-->
    <el-dialog
      :visible.sync="partsDialogVisible"
      width="500px"
      class="partsForm-dialog">
      <span slot="title" class="custom-dialog-title">添加配件信息</span>
      <el-form ref="partsForm" :model="partsForm" :rules="rulesParts" label-width="100px">
        <el-form-item label="配件名" prop="partsName">
          <el-input v-model="partsForm.partsName"></el-input>
        </el-form-item>
        <el-form-item label="原配件SN" prop="originPartsSnId">
          <el-input v-model="partsForm.originPartsSnId"></el-input>
        </el-form-item>
        <el-form-item label="新配件SN" prop="newPartsSnId">
          <el-input v-model="partsForm.newPartsSnId"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="partsDialogVisible = false">取消</el-button>
        <el-button type="success" @click="submitParts">提交</el-button>
      </span>

    </el-dialog>


    <!-- 物流信息弹窗 -->
    <el-dialog
      :visible.sync="wuliuDialogVisible"
      width="500px">
      <span slot="title" class="custom-dialog-title">机器售后物流信息</span>
      <el-form ref="wuliuForm" :model="wuliuForm" :rules="rulesWuliu" label-width="100px">
        <el-form-item label="产品条码" prop="snId">
          <el-input v-model="wuliuForm.snId" disabled></el-input>
        </el-form-item>
        <el-form-item label="物流公司" prop="logistics">
          <el-select v-model="wuliuForm.logistics" placeholder="请选择物流公司">
            <el-option label="德邦快递" :value="1"></el-option>
            <el-option label="顺丰速递" :value="2"></el-option>
            <el-option label="中通快递" :value="3"></el-option>
            <el-option label="申通快递" :value="4"></el-option>
            <el-option label="邮政快递" :value="5"></el-option>
            <el-option label="韵达快递" :value="6"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsId">
          <el-input v-model="wuliuForm.logisticsId"></el-input>
        </el-form-item>
        <el-form-item label="客户名称" prop="client">
          <el-input v-model="wuliuForm.client"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="wuliuDialogVisible = false">返回</el-button>
        <el-button type="primary" @click="submitWuliu">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import {
  getShouhouInfoList,
  shouhouSend,
  addShouhouInfo,
  updateShouhou,
  shouhouWeixiu,
  loadList,
  addShouhouWuliu,
  partsQuery,
  partsAdd,
  partsDelete
} from "@/api/Empment/shouhoumaintain";
import {Message} from 'element-ui';

export default {
  name: "EpmShouhouMaintain",
  data() {
    return {
      tableData: [],
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        snId: "",
        sendBackNumber: "",
      },

      // 修改数据表单
      updateDialogVisible: false,
      updateForm: {
        sendBackNumber: "",
        snId: "",
        name: "",
        brand: "",
        machineType: "",
        size: null,
        count: null,
        manuDate: null,
        attachStatus: "",
        backLocation: "",
        phenomenon: ""
      },


      // 显示详细数据表单
      detailsDialogVisible: false, // 控制详情弹窗的显示
      detailsForm: {
        sendBackNumber: "",
        snId: "",
        name: "",
        brand: "",
        machineType: "",
        size: null,
        count: null,
        attachStatus: "",
        failureCondition: null,
        phenomenon: "",
        backLocation: "",
        manuDate: null,
        backDate: null
      },


      // 添加数据表单
      addDialogVisible: false, // 控制显示列表或添加表单
      addForm: {
        sendBackNumber: "",
        snId: "",
        name: "",
        brand: "",
        machineType: "",
        size: null,
        count: null,
        manuDate: null,
        attachStatus: "",
        backLocation: "",
        phenomenon: ""
      },


      // 维修数据表单
      weixiuDialogVisible: false, // 控制显示列表或添加表单
      weixiuForm: {
        snId: "",
        brokedown: "",
        maintainRecord: "",
        badReason: "",
        resolveMethod: "",
        responsibility: null,
        maintainMan: "",
        maintainPoint: null,
        other: ""
      },


      // 添加配件信息表单
      partsDialogVisible: false,
      partsTableVisible: false,
      partsTableForm: [],
      partsForm: {
        snId: "",
        partsName: "",
        originPartsSnId: "",
        newPartsSnId: ""
      },


      // 物流数据表单
      wuliuDialogVisible: false,
      wuliuForm: {
        snId: "",
        logistics: null,
        logisticsId: "",
        client: ""
      },


      // 表单验证规则
      rulesAdd: {
        snId: [
          {required: true, message: '机器SN码不能为空', trigger: 'blur'}
        ],
        sendBackNumber: [
          {required: true, message: '快递单号不能为空', trigger: 'blur'}
        ]
      },
      rulesUpdate: {
        snId: [
          {required: true, message: '机器SN码不能为空', trigger: 'blur'}
        ],
        sendBackNumber: [
          {required: true, message: '快递单号不能为空', trigger: 'blur'}
        ]
      },
      rulesWuliu: {
        logistics: [
          {required: true, message: '物流公司信息不能为空', trigger: 'blur'}
        ],
        logisticsId: [
          {required: true, message: '物流单号信息不能为空', trigger: 'blur'}
        ]
      },
      rulesParts:{
        originPartsSnId:[
          {require:true, message: '原SN码不能为空', trigger: 'blur'}
        ],
        newPartsSnId:[
          {require:true, message: '新SN码不能为空', trigger: 'blur'}
        ]
      }

    };
  },


  methods: {
    // 加载数据
    getList() {
      this.fetchData();
    },
    fetchData() {
      this.loading = true;
      getShouhouInfoList(this.queryParams)
        .then(response => {
          this.tableData = response.rows;
          this.loading = false;
          this.total = response.total;
        })
        .catch(error => {
          console.error("加载数据时出现错误:", error);
          this.loading = false;
        });
    },


    // 更新七天失效情况
    loadFailureCondition() {
      this.loading = true; // 开始加载状态
      loadList(this.queryParams)
        .then(response => {
          // 如果后端有返回数据，直接更新 tableData
          if (response && response.rows) {
            this.tableData = response.rows; // 更新表格数据
            this.total = response.total; // 更新总数
          }
        })
        .catch(error => {
          console.error("加载数据时出现错误:", error);
        })
        .finally(() => {
          this.fetchData();
          this.loading = false; // 结束加载状态
        });
    },


    // 修改数据
    openUpdateDialog(row) {
      this.updateForm = {...row};
      this.updateDialogVisible = true;
    },
    submitUpdate() {
      this.$refs.updateForm.validate((valid) => {
        if (valid) {
          // 验证通过后提交数据
          updateShouhou(this.updateForm)
            .then(() => {
              Message.success('信息修改成功');
              this.updateDialogVisible = false;
              this.fetchData(); // 重新加载数据
            })
            .catch(error => {
              console.error('修改时出现错误:', error);
              Message.error('修改失败');
            });
        } else {
          Message.error('请填写必填项');
        }
      });
    },


    // 添加弹窗,确保每次打开后表单为空
    showAddForm() {
      this.addForm = {
        sendBackNumber: "",
        snId: "",
        name: "",
        brand: "",
        machineType: "",
        size: null,
        count: null,
        manuDate: null,
        attachStatus: "",
        backLocation: "",
        phenomenon: ""
      };
      this.addDialogVisible = true; // 显示添加弹窗
    },


    // 添加数据
    submitAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addShouhouInfo(this.addForm)
            .then(() => {
              Message.success('添加成功');
              this.addDialogVisible = false;
              this.fetchData(); // 重新加载数据
            })
            .catch(error => {
              Message.error('添加失败');
            });
        } else {
          // 验证失败
          Message.error('请填写必填项');
        }
      });
    },


    // 显示维修弹窗
    openWeixiuDialog(row) {
      this.weixiuForm = {...row};
      this.weixiuDialogVisible = true;
    },

    submitWeixiu() {
      shouhouWeixiu(this.weixiuForm)
        .then(() => {
          Message.success('维修记录提交成功');
          this.weixiuDialogVisible = false;
          this.fetchData(); // 重新加载数据
        })
        .catch(error => {
          console.error('维修记录提交时出现错误:', error);
          Message.error('维修记录提交失败');
        });
    },


    // 查看配件数据
    addPartsInfomation(snId) {
      this.partsForm.snId = snId; // 记录该商品的snId
      partsQuery(snId)
        .then(response => {
          this.partsTableForm = response.rows;
          this.partsTableVisible = true;
        })
        .catch(error => {
          console.error("配件信息查询失败:", error);
          this.$message.error("配件信息查询失败，请稍后重试。");
        });
    },


    // 打开添加配件信息对话框
    addParts() {
      this.partsForm = {
        snId: this.partsForm.snId,
        partsName: "",
        originPartsSnId: "",
        newPartsSnId: ""
      };
      this.partsDialogVisible = true; // 显示添加对话框
    },

    // 提交配件数据
    submitParts() {
      partsAdd(this.partsForm)
        .then(() => {
          this.$message.success('提交成功');
          this.partsDialogVisible = false;

          // 重新加载数据
          return partsQuery(this.partsForm.snId);
        })
        .then(response => {
          this.partsTableForm = response.rows; // 更新表格数据
        })
        .catch(() => {
          this.$message.error('提交失败');
        });
    },

    // 删除配件数据
    deletePartsData(row) {
      this.$confirm('确认删除该配件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用删除接口
          return partsDelete(row.id);
        })
        .then(() => {
          this.$message.success('删除成功');
          // 从表格中移除已删除的配件
          this.partsTableForm = this.partsTableForm.filter(item => item.id !== row.id);
        })
        .catch(() => {
          this.$message.info('已取消删除');
        });
    },


    // 发货
    openWuliuDialog(row) {
      // 判断 machineCondition 是否为 2
      if (row.machineCondition !== 2) {
        this.$message.error('请优先进行维修操作');
        return;
      }
      // 如果 machineCondition 为 2，打开物流对话框
      this.wuliuForm = {
        snId: row.snId,       // 初始化物流表单
        logistics: null,
        logisticsId: "",
        client: ""
      };
      this.wuliuDialogVisible = true;
    },

    submitWuliu() {
      this.$refs.wuliuForm.validate((valid) => {
        if (valid) {
          // 如果验证通过，提交数据
          addShouhouWuliu(this.wuliuForm)
            .then(() => {
              // 成功插入物流信息后，执行发货操作
              return shouhouSend(this.wuliuForm.snId);
            })
            .then(() => {
              this.$message.success('发货成功');
              this.wuliuDialogVisible = false;
              this.fetchData(); // 重新加载数据
            })
            .catch(error => {
              console.error('出现错误:', error);
              Message.error('发货失败');
            });
        } else {
          // 如果验证未通过，提示用户
          Message.error('请填写必填项');
          return false;
        }
      });
    },


    // 显示订单详情
    showDetailsDialog(row) {
      this.detailsForm = {
        ...row,
        manuDate: this.formatDate(row.manuDate), // 格式化生产日期
        backDate: this.formatDate(row.backDate)  // 格式化退回日期
      };// 将选中行的数据填充到 detailsForm
      this.detailsDialogVisible = true; // 打开详情弹窗
    },


    // //动态重置表单
    // onReset(form) {
    //   this.$refs[form].resetFields();
    // }

    // 格式化时间
    formatDate(isoDate) {
      if (!isoDate) return ""; // 处理空日期
      const date = new Date(isoDate);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
  },

  mounted() {
    this.fetchData(); // 组件挂载后加载数据
  }
};
</script>

<style>
.custom-dialog-title {
  font-size: 18px; /* 加大字号 */
  font-weight: bold; /* 加粗字体 */
}

.load-failure-position {
  position: absolute;
  left: 1150px;
}

.partsForm-dialog {
  margin-top: 180px;
}

.partsTable-dialog {
  margin-top: 50px;
}
</style>
